/*
 * Copyright 2011-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.sabayframework.cluster.impl;

import java.lang.reflect.Array;
import java.util.Iterator;

import org.sabayframework.cluster.NodeId;
import org.sabayframework.cluster.NodeMapping;


public class ModuloNodeMapping<T extends NodeId> implements NodeMapping {

	private T[] nodes;
	
	public ModuloNodeMapping(T[] nodes) {
		if(nodes.length==0) throw new IllegalArgumentException("Array length must be greater than 0");
		this.nodes = nodes;
	}

	public T get(final int key)	{
		return nodes[ (key < 0 ? -key : key) % nodes.length];
	}

	@SuppressWarnings("unchecked")
	public T[] nearest(final int key,final int n) {
		final T[] res=(T[])Array.newInstance(nodes.getClass().getComponentType(), Math.min(n, nodes.length));
		int index = (key < 0 ? -key : key) % nodes.length;
		for(int i=0;i<res.length;++i){
			res[i] = nodes[index];
			index = (index+1) % nodes.length;
		}
		return res;
	}

	public Iterator<T> iterate(final int key) {
		return new Iterator<T>() {
			private int i = (key < 0 ? -key : key) % nodes.length;
			public boolean hasNext() {
				return true;
			}
			public T next() {
				T n = nodes[i];
				i = (i+1) % nodes.length;
				return n;
			}
			public void remove() {}
		};
	}
}
